<template>
  <el-container class="main-container">
    <el-container>
      <el-container>
        <el-main>
          <div class="payment-info">
            <el-row class="toolbar">
              <el-col :span="12" class="search-area">
                <el-input
                  v-model="searchForm.recordId"
                  placeholder="Search by Record ID"
                  clearable
                  class="search-input">
                </el-input>
                <el-button type="primary" icon="el-icon-search" @click="getPaymentById">Pay</el-button>

                <el-select v-model="searchForm.paymentMethod" placeholder="Select Payment Method" clearable class="search-input">
                  <el-option label="Cash" value="Cash"></el-option>
                  <el-option label="Credit Card" value="Credit Card"></el-option>
                  <el-option label="Mobile Payment" value="Mobile Payment"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="searchByPaymentMethod">Me</el-button>

                <el-select v-model="searchForm.paymentStatus" placeholder="Select Payment Status" clearable class="search-input">
                  <el-option label="Pending" value="Pending"></el-option>
                  <el-option label="Completed" value="Completed"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" @click="searchPayments">Sta</el-button>
                <el-button type="default" @click="fetchAllPayments">Fetch All Payments</el-button>
                <el-button type="default" @click="navigateTo('User')">Go to UserInfo</el-button>
              </el-col>
              <el-col :span="12" class="action-area">
                <el-button type="success" icon="el-icon-plus" @click="openAddDialog">Add Payment Record</el-button>
              </el-col>
            </el-row>

            <!-- Payment Info Table -->
            <el-table :data="currentPayments" stripe border :row-class-name="tableRowClassName">
              <el-table-column label="No." width="60" type="index" :index="calculateIndex" />
              <el-table-column prop="paymentId" label="Payment ID" width="100" />
              <el-table-column prop="recordId" label="Record ID" />
              <el-table-column prop="paymentMethod" label="Payment Method" />
              <el-table-column prop="paymentStatus" label="Payment Status" />
              <el-table-column prop="amount" label="Amount" />
              <el-table-column label="Actions" width="180">
                <template slot-scope="scope">
                  <el-button size="small" type="text" @click="openEditDialog(scope.row)">Edit</el-button>
                  <el-button size="small" type="text" @click="deletePayment(scope.row.paymentId)">Delete</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- Pagination -->
            <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :total="totalPayments"
                @current-change="handlePageChange">
            </el-pagination>

            <!-- Add/Edit Dialog -->
            <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
              <el-form :model="paymentForm" label-width="120px">
                <el-form-item label="Payment ID">
                  <el-input v-model="paymentForm.paymentId" disabled></el-input>
                </el-form-item>
                <el-form-item label="Record ID">
                  <el-input v-model="paymentForm.recordId"></el-input>
                </el-form-item>
                <el-form-item label="Payment Method">
                  <el-select v-model="paymentForm.paymentMethod">
                    <el-option label="Cash" value="Cash"></el-option>
                    <el-option label="Credit Card" value="Credit Card"></el-option>
                    <el-option label="Mobile Payment" value="Mobile Payment"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="Payment Status">
                  <el-select v-model="paymentForm.paymentStatus">
                    <el-option label="Pending" value="Pending"></el-option>
                    <el-option label="Completed" value="Completed"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="Amount">
                  <el-input
                    type="number"
                    v-model="paymentForm.amount"
                    @input="validateAmount">
                  </el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="savePayment">Save</el-button>
              </div>
            </el-dialog>

          </div>
        </el-main>
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
import { getPaymentById, getAllPayments, addPayment, updatePayment, deletePayment } from '@/api/paymentInfo';

export default {
  name: 'PaymentInfo',
  data() {
    return {
      payments: [],
      currentPayments: [],
      totalPayments: 0, // 总支付记录数
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的支付记录数量
      searchForm: {
        recordId: '',
        paymentMethod: '',  // 新增支付方式条件
        paymentStatus: ''   // 新增支付状态条件
      },
      paymentForm: {
        paymentId: null,
        recordId: '',
        paymentMethod: '',
        paymentStatus: '',
        amount: 0
      },
      dialogVisible: false,
      dialogTitle: '',
    };
  },
  computed: {
    filteredPayments() {
      if (!Array.isArray(this.payments)) {
        return [];
      }
      return this.payments; // 这里可以添加更复杂的筛选逻辑
    }
  },
  methods: {
    navigateTo(routeName) {
      this.$router.push({ name: routeName }).catch(err => {
        if (err.name != 'NavigationDuplicated') {
          throw err;
        }
      });
    },
    fetchAllPayments() {
      getAllPayments().then(response => {
        this.payments = response; // 获取所有支付记录
        this.totalPayments = response.length; // 更新总支付记录数
        this.updateCurrentPayments(); // 更新当前支付记录数据
      });
    },
    updateCurrentPayments() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.currentPayments = this.payments.slice(start, end); // 根据索引获取当前支付记录
    },
    handlePageChange(page) {
      this.currentPage = page; // 更新当前页码
      this.updateCurrentPayments(); // 更新当前显示的支付记录
    },
    searchPayments() {
      const { recordId, paymentMethod, paymentStatus } = this.searchForm;
      this.currentPayments = this.payments.filter(payment => {
        const matchesRecordId = recordId ? payment.recordId.includes(recordId) : true;
        const matchesPaymentMethod = paymentMethod ? payment.paymentMethod === paymentMethod : true;
        const matchesPaymentStatus = paymentStatus ? payment.paymentStatus === paymentStatus : true;

        return matchesRecordId && matchesPaymentMethod && matchesPaymentStatus;
      });

      // 更新总记录数
      this.totalPayments = this.currentPayments.length;
    },
    searchByPaymentMethod() {
      const paymentMethod = this.searchForm.paymentMethod;
      if (paymentMethod) {
        this.currentPayments = this.payments.filter(payment => payment.paymentMethod === paymentMethod);
        this.totalPayments = this.currentPayments.length; // 更新总记录数
      } else {
        this.fetchAllPayments(); // 如果没有选择支付方式，获取所有支付记录
      }
    },
    getPaymentById() {
      const recordId = this.searchForm.recordId;
      if (recordId) {
        getPaymentById(recordId).then(response => {
          if (response) {
            this.currentPayments = [response]; // 返回找到的记录
          } else {
            this.currentPayments = []; // 没有记录
            this.$message.warning('未找到记录'); // 提示用户
          }
        }).catch(error => {
          console.error('Error fetching payment by ID:', error);
          this.$message.error('查询出错，请重试'); // 提示用户
        });
      } else {
        this.fetchAllPayments(); // 如果记录 ID 为空，获取所有支付记录
      }
    },
    openAddDialog() {
      this.dialogTitle = 'Add Payment Record';
      this.paymentForm = { paymentId: null, recordId: '', paymentMethod: 'Cash', paymentStatus: 'Pending', amount: 0 };
      this.dialogVisible = true;
    },
    openEditDialog(payment) {
      this.dialogTitle = 'Edit Payment Record';
      this.paymentForm = { ...payment }; // 填充支付数据
      this.dialogVisible = true;
    },
    savePayment() {
      const apiCall = this.paymentForm.paymentId ? updatePayment(this.paymentForm) : addPayment(this.paymentForm);
      apiCall.then(() => {
        this.fetchAllPayments(); // 刷新支付记录列表
        this.dialogVisible = false; // 关闭对话框
      });
    },
    deletePayment(paymentId) {
      this.$confirm('Are you sure to delete this payment record?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        deletePayment(paymentId).then(() => {
          this.fetchAllPayments(); // 刷新支付记录列表
        });
      });
    },
    validateAmount() {
      if (this.paymentForm.amount < 0) {
        this.paymentForm.amount = 0; // 如果为负数，将其重置为 0
        this.$message.warning('Amount cannot be negative'); // 提示用户
      }
    },
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    tableRowClassName(row, index) {
      return index % 2 ? 'even-row' : 'odd-row';
    }
  },
  mounted() {
    this.fetchAllPayments(); // 组件挂载时获取所有支付记录
  }
};
</script>

<style>
.payment-info {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.action-area .el-button {
  margin-left: 10px;
}
</style>
